/**
 * Basic creature creation & management
 */
import { addEntity, addComponent } from 'bitecs';
import { placeOnMap } from './pos2';
import { Glyph, Creature, Player, Collision, AI, Description } from './components';
import { decode, encode } from './util';
import { Inventory } from './inventory';
import { VisualMemory } from './memory';
import { Eyes } from './eyes';
import { Clock } from './clock';
import { fromTemplate } from './builder';

// TODO: move out of lib to psychic
export const pcTemplate = [
  [Creature],
  [Player],
  [Description, {
    summary: 'human',
    description: "That's you",
  }],
  [Glyph, {
    glyph: '@',
    color: '#fff',
  }],
  [Collision],
  [VisualMemory],
  [Eyes, {
    range: 14,
  }],
  [Inventory, {
    size: 16,
    count: 0,
  }],
  [Clock],
];

const newCreature = (world, glyph: string, creature: string, invsize: number | null) => {
  const e = addEntity(world);
  addComponent(world, Glyph, e);
  addComponent(world, Creature, e);
  addComponent(world, Clock, e);
  addComponent(world, Collision, e);
  addComponent(world, Description, e);
  if (invsize !== undefined) {
    addComponent(world, Inventory, e);
    Inventory.size[e] = invsize;
    Inventory.count[e] = 0;
  }
  Glyph.glyph[e] = encode(glyph);
  Description.summary[e].set(encode(creature));
  Clock.created[e] = 0;
  Clock.time[e] = 0;
  return e;
};

export const addPc = (world, x, y) => {
  const pc = fromTemplate(world, pcTemplate);
  placeOnMap(world, pc, x, y);
  return pc;
};

export const addRat = (world) => {
  const rat = newCreature(world, 'r', 'rat');
  addComponent(world, AI, rat);
  placeOnMap(world, rat, 7, 8);
};
